// https://cn.vitejs.dev/guide/features.html#glob-import
import { CustomRoute, defaultOrder, PluginConfig } from '@/interface'
import { BasicLayout } from '@/layouts'
import { pluginPrefixPath, pluginRouteName } from './setting'

const pluginConfigs = Object.values(
  import.meta.glob('./*Plugin/index.ts', { eager: true, import: 'pluginConfig' })
) as PluginConfig[]

const plugins = pluginConfigs
  .filter((v) => v.enable !== false)
  .map((v) => {
    v.order = v.order || defaultOrder
    return v
  })
  .sort((a, b) => (a.order! > b.order! ? 1 : -1))
  .map((pluginConfig) => {
    const name = pluginRouteName + '-' + pluginConfig.name
    const path = pluginPrefixPath + (pluginConfig.path || '/' + name)
    const title = pluginConfig.title || name
    const children = pluginConfig.children
      .filter((v) => v.enable !== false)
      .map((item) => {
        const childName = name + '-' + item.name
        const childPath = path + (item.path || '/' + item.name)
        const childTitle = item.title || item.name
        const child: CustomRoute = {
          name: childName,
          component: item.component,
          path: childPath,
          meta: {
            title: childTitle,
            keepAlive: item.keepAlive,
          },
        }
        return child
      })
    const plugin: CustomRoute = {
      name,
      component: BasicLayout,
      path,
      meta: {
        title,
        icon: pluginConfig.icon,
      },
      children,
    }
    return plugin
  })

export const pluginRoutes: CustomRoute[] = Object.values(plugins) as CustomRoute[]
